package com.ruoyi.ai.service.url;

import cn.hutool.core.util.URLUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;

@Service
public class DomainService {

    @Autowired
    private RuoYiConfig ruoYiConfig;

    /**
     * 替换为当前访问的域名
     * 两种情况：第一种，不是http或者https开头的，必须拼接上域名，不然不能用
     * 第二种，已经有http或者https开头的，按照配置来决定是否替换域名
     *
     * @param url
     * @return
     */
    public String replaceCurrentDomainName(String url, String prefix) {
        if(StringUtils.isEmpty(url)){
            return url;
        }
        url = this.handlerReplaceCurrentDomain(url, prefix);
        return this.handlerReplaceProtocol(url);
    }

    public String handlerReplaceCurrentDomain(String url, String prefix) {
        url = fullUrl(url);
        if (!Objects.equals(ruoYiConfig.getReplaceDomain(), true)) {
            return url;
        }
        if (StringUtils.isEmpty(url)) {
            return url;
        }
        if (prefix == null) {
            prefix = "";
        }
        String domain;
        if (StringUtils.isEmpty(ruoYiConfig.getReplaceDomainUrl())) {
            domain = getUrl();
        } else {
            domain = ruoYiConfig.getReplaceDomainUrl();
        }
        return replaceDomainName(url, domain, prefix);
    }

    public String handlerReplaceProtocol(String url) {
        if (Objects.equals(ruoYiConfig.getTransToHttps(), true)) {
            url = url.replace("http://", "https://");
        }
        return url;
    }

    public String fullUrl(String url) {
        if (url.startsWith("http:") || url.startsWith("https:")) {
            return url;
        }
        return getUrl() + "/" + url;
    }

    /**
     * 外部渠道替换图片域名
     * 例如小程序发布体验版，用内网穿透域名访问，这时候必须将localhost域名替换，不然访问不到
     */
    public String replaceDomainName(String url, String domain, String prefix) {
        try {
            String urlEncode = URLUtil.encode(url);
            String path = URLUtil.getPath(urlEncode);
            path = URLUtil.decode(path);
            return domain + prefix + path;
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    /**
     * 获取完整的请求路径，包括：域名，端口，上下文访问路径
     *
     * @return 服务地址
     */
    public String getUrl() {
        HttpServletRequest request = ServletUtils.getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
}
